package com.store.app.net;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;

import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.http.Stores;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.push.PushUtils;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/1/18.
 * 网络请求的基类
 */
public class BaseHttpRequest {
    public AjaxCallBack<Object> ajaxcallback;    // 回调接口
    public static boolean isShowDialog = false;  // 请求时是否显示黑色圈圈
    private  static FinalHttp fh;                 // 请求对象
    private FinalBitmap fb;                     // 请求图片
    private IOnHttpListener httpListener;       // 请求接口回调
    private final static int HANDLER_WHAT_SUCESS = 0;
    private final static int HANDLER_WHAT_FAIL = 1;
    private final static int HANDLER_WHAT_NET = 2;
    private final static int EXIT = 3;
    private Context context;
    /**
     * 把服务器原始结果进行处理
     */
    private Handler baseHandler = new Handler() {
        public void handleMessage(Message msg) {
            ResultEntity result = (ResultEntity) msg.obj;
            switch (msg.what) {
                case HANDLER_WHAT_SUCESS:
                    if (httpListener != null)
                        httpListener.onExecuteSuccess(result.requestId, result.data, result.msg);
                    break;
                case HANDLER_WHAT_FAIL:
                    if (httpListener != null)
                        httpListener.onExecuteFail(result.requestId, result.msg);
                    break;
                case HANDLER_WHAT_NET:
                    if (httpListener != null)
                        httpListener.onAfinalFail();
                    break;
                case EXIT:
                    Log.v("zyl", "去退出");
                    try {
                        PushUtils.setTags(context,null,null);
                        PushUtils.setAlias(context,"", null);
                        SharedPreferences preferences;
                        preferences = PreferenceManager.getDefaultSharedPreferences(context);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString(MainActivity.PREF_APP_TOKEN, "").commit();
                        editor.putString(MainActivity.PREF_SECURITY_CODE, "").commit();
                        editor.putString(MainActivity.PREF_USER_TOKEN, "").commit();
                        editor.putString(MainActivity.PREF_USER_SECURITY_CODE, "").commit();
                        editor.putString(MainActivity.PREF_MEMBER_ID, "").commit();
                        editor.putString("member_id", "").commit();
                        editor.putString("area_id", "").commit();
                        editor.putString("stores_name", "").commit();
                        editor.putString("store_desc", "").commit();
                        editor.putString("contact_person", "").commit();
                        editor.putString("stores_type_key", "").commit();
                        editor.putString("business_type_key", "").commit();
                        editor.putString("contact_tel", "").commit();
                        editor.putString("address", "").commit();
                        editor.putString("neighbor_pic_path", "").commit();
                        editor.putString("longitude", "").commit();
                        editor.putString("latitude", "").commit();
                        Log.v("zyl", "跳转到首页");
                       // HyphenateHelper.getInstance().logout(false, null);
                        Intent intent = new Intent();
                        intent.putExtra("log_again", "true");
                        intent.setClass(context, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                        ExitApplication.getInstance().exit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v("zyl", "跳到登录页面失败");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public BaseHttpRequest(Context context) {
        this.context = context;
        fh = getFh();
        fb = FinalBitmap.create(context);
    }

    public static FinalHttp getFh() {
        if (fh == null) {
            fh = new FinalHttp();
            fh.configTimeout(30 * 1000); // 设置超时连接 10秒
        }
        return fh;
    }



    public void setHttpListener(IOnHttpListener httpListener) {
        this.httpListener = httpListener;
    }

    /**
     * 添加请求参数，执行网络请求
     *
     * @param requestId
     * @param ifShowDialog
     */
    public void requestData(String serviceAction, int requestId, boolean ifShowDialog, AjaxParams params) {
        try {
            Log.v("zyl", "requestData");
            String url = Stores.http;
            //如果不为空，说明有需要想服务器提交的数据
            if (params == null) {
                params = new AjaxParams();
            }
//            params.put("version", "3.3.0");
//            params.put("platform", "android");
            doPostRquest(serviceAction, requestId, url, params, ifShowDialog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    public void uploadPic(final int requestId,AjaxParams params){
        FinalHttp fh = new FinalHttp();
        Log.i("zyl", "requestURL：" + Stores.http + "/ops-storage/storage/upload"+ "?" + params.toString());
        fh.post(Stores.http + "/ops-storage/storage/upload", params, new AjaxCallBack(){
            @Override
            public void onLoading(long count, long current) {
                Log.v("zyl","onLoading："+current+"/"+count);
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                String result = o.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String rspCode = json.getString("rsp_code");
                    Log.v("zyl", "onSuccess:" + result);
                    if (rspCode.equals("succ")) {
                        String data = json.getString("data");
                        ResultEntity resultEntity = new ResultEntity("", data, requestId);
                        Message message = new Message();
                        message.what = HANDLER_WHAT_SUCESS;
                        message.obj = resultEntity;
                        baseHandler.sendMessage(message);
                    } else {
                        String msg = json.getString("error_msg");
                        if (msg.contains("token")) {
                            Log.v("zyl", "包含token");
//                            Toast.makeText(context, "您的账号已在其他手机登录，请重新登陆！", Toast.LENGTH_LONG).show();
                            baseHandler.sendEmptyMessageDelayed(EXIT, 0);
//                                ((Activity) context).finish();
                        }
                        else {
                            Message message = new Message();
                            message.what = HANDLER_WHAT_FAIL;
                            if(msg.contains("参数缺失")){
                                msg="登录信息丢失,请重新登录";
                            }
                            ResultEntity resultEntity = new ResultEntity(msg, "", requestId);
                            message.obj = resultEntity;
                            baseHandler.sendMessage(message);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.v("zyl","上传图片网络不通："+strMsg);
            }
        });
    }






    public void doPostRquest(String serviceAction, final int requestId, String url, AjaxParams params,
                             final boolean ifShowDialog) {
        Log.i("zyl", "requestURL：" + url + serviceAction + "?" + params.toString());
        fh.post(url + serviceAction, params, ajaxcallback = new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
//                Log.v("zyl", "onStart");
                if (isShowDialog) {

                }
            }

            @Override
            public void onSuccess(Object t) {
                super.onSuccess(t);
                String result = t.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String rspCode = json.getString("rsp_code");
                    Log.v("zyl", "onSuccess:" + result);
                    if (rspCode.equals("succ")) {
                        String data = json.getString("data");
//                        String data = json.getJSONObject("data").toString();

//                        String data = json.optJSONObject("data").toString();
//                        Log.v("zyl","解析的data:"+data);
//                        if(TextUtils.isEmpty(data)){
//                            data = json.optJSONArray("data").toString();
//                        }
                        ResultEntity resultEntity = new ResultEntity("", data, requestId);
                        Message message = new Message();
                        message.what = HANDLER_WHAT_SUCESS;
                        message.obj = resultEntity;
                        baseHandler.sendMessage(message);
                    } else {
                        String msg = json.getString("error_msg");
//                        Log.v("zyl", "msg1:" + msg);
//
//                        Log.v("zyl", "msg2:" + msg);
//                        Log.v("zyl", "onFailure:" + msg);
                        if (msg.contains("token")) {
                            Log.v("zyl", "包含token");
//                            Toast.makeText(context, "您的账号已在其他手机登录，请重新登陆！", Toast.LENGTH_LONG).show();
                            baseHandler.sendEmptyMessageDelayed(EXIT, 0);
//                                ((Activity) context).finish();
                        }
                        else {
                            Message message = new Message();
                            message.what = HANDLER_WHAT_FAIL;
                            if(msg.contains("参数缺失")){
                                msg="登录信息已丢失，请重新登录";
                            }
                            ResultEntity resultEntity = new ResultEntity(msg, "", requestId);
                            message.obj = resultEntity;
                            baseHandler.sendMessage(message);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            /**
             * 处理请求失败的回调函数
             */
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Log.i("zyl", "onAfinalFail:" + strMsg);
                super.onFailure(t, errorNo, strMsg);
                Message message = new Message();
                message.what = HANDLER_WHAT_NET;
                baseHandler.sendMessage(message);
            }
        });
    }

    public class ResultEntity {
        String msg;
        String data;
        int requestId;

        public ResultEntity(String msg, String data, int requestId) {
            this.msg = msg;
            this.data = data;
            this.requestId = requestId;
        }
    }
}
